import { ChangeDetectionStrategy, Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';
// import { ProductNotes } from './../../core/class/product-note';
import { ProductNotes } from '../../core/class/product-note';
import { ProductService } from '../../core/services/product.service';
import { Subscription } from 'rxjs/Subscription';
import { CustomValidators } from '../../share/validators/custom-form.validators';
import { ToasterService } from '../../share/toastr/toastr.service';


@Component({
  selector: 'app-add-note',
  templateUrl: './add-note.html',
  styleUrls: ['./add-note.css'],
  providers: [BsModalService],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AddNoteComponent implements OnInit {


  @Input() productNote: ProductNotes = {
    content:  '',
    addDate:  '',
    isSetTop: ''
  };

  @Input('noteList') notes: any[];

  @Output() onSubmit    = new EventEmitter<ProductNotes>();
  @Output() deleteNotes = new EventEmitter<ProductNotes>();
  @Output() modifyNotes = new EventEmitter<ProductNotes>();

  noteSubs: Subscription;
  form:    FormGroup;
  date:    any;
  istops:  boolean;
  content: any;
  formSubmit = false;


  constructor(
    public  bsModalRef:     BsModalRef,
    public  formBuilder:    FormBuilder,
    private addNoteService: ProductService,
    public  toastrService:  ToasterService
  ) { }


  ngOnInit() {
    this.initForm();

  }

  initForm() {
    this.form = this.formBuilder.group({
      'content':  [this.productNote.content, [Validators.required]],
      'addDate':  [this.productNote.addDate, [Validators.required]],
      'isSetTop': [this.productNote.isSetTop]
    });
    this.istops = false;
  }


  submit() {
    const values = this.form.value;
    const keys   = Object.keys(values);
    this.formSubmit = true;

    if (this.form.valid) {
      console.log('form valid : ', this.form.valid);
      this.noteSubs = this.addNoteService.AddNote(values)
          .subscribe(data => {
            const errors = data.errors;
            if (errors) {
              keys.forEach(val => {
                if (errors[val]) { this.pushError(val, errors)}
              });
            }
          });
          this.toastrService.successful('Add Product Note, Successfuly !');
          this.bsModalRef.hide();
          } else {
            // this.toastrService.errors('Add Product Note, Error !');
            keys.forEach(val => {
              const ctrl = this.form.controls[val];
              if (!ctrl.valid) {
                this.pushError(val, null);
                ctrl.markAsTouched();
              };
            });
          }
        }

  private pushError(ctrl_name: string, msg: string) {
    this.form.controls[ctrl_name].setErrors({'msg': msg});
  }


}
